<template>
  <el-card class="container">
    <div class="page-box">
      <div class="search-box">
        <el-form ref="form" :inline="true" class="demo-form-inline">
          <el-input v-model="queryParmas.role_name" placeholder="角色名称" clearable autocomplete="off" type="text" style="width: 219px;margin-right: 10px;border-radius: 4px;" />
          <el-form-item>
            <el-button type="primary" plain style="border-radius: 4px;" @click="btnSeacher">搜索</el-button>
            <el-button plain style="border-radius: 4px;" @click="btnReset">重置</el-button>
          </el-form-item>
          <el-button type="primary" plain style="position: absolute; top: 80px; right: 60px;border-radius: 4px;" @click="addRole">创建角色</el-button>
        </el-form>
      </div>
      <div class="table-box">
        <el-table
          :data="list"
          style="width: 100% "
          border
        >
          <el-table-column prop="id" label="角色ID" width="140" />
          <el-table-column label="角色名称" width="191" prop="role_name" />
          <el-table-column label="角色标识" width="189" prop="identify" />
          <el-table-column label="角色描述" width="300" prop="description" />
          <el-table-column label="添加时间" width="189" prop="updated_at">
            <template slot-scope="scope">
              <p>{{ new Date(scope.row.updated_at) | dateFormat }}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{row}">
              <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="editRole(row.id)" />
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteRole(row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-row type="flex" justify="end">
          <el-pagination
            background
            :current-page="queryParmas.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryParmas.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
      <el-dialog :visible.sync="showDialog" :title="title" @close="resetForm">
        <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="role_name">
            <el-input v-model="formData.role_name" placeholder="请输入角色名称" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="角色标识" prop="identify">
            <el-input v-model="formData.identify" placeholder="请输入角色标识" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formData.description" placeholder="请输入角色描述" type="textarea" rows="2" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="角色权限" prop="authlist">
            <el-tree
              ref="tree"
              v-model="formData.authlist"
              show-checkbox
              node-key="id"
              :data="dataList"
              :props="{children: 'children', label: 'permission_name'}"
              :default-checked-keys="defaultChecked"
              highlight-current
              :current-node-key="true"
              :check-strictly="true"
            />
          </el-form-item>
          <el-row type="flex" justify="end">
            <el-button size="mini" @click="cancelForm">取消</el-button>
            <el-button type="primary" size="mini" @click="submit">确定</el-button>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { getRoleList, deleteRole, updateRole, getRoleDetail, addRoleList } from '@/api/permission/role'
// import { transListToTreeData } from '@/utils'
import { getMenu } from '@/api/permission/menu'
import moment from 'moment'
export default {
  filters: {
    dateFormat: function(date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      dataList: [],
      formData: {
        role_name: '',
        identify: '',
        description: '',
        authlist: []
      },
      defaultChecked: [],
      rules: {
        role_name: [{
          required: true, message: '请输入角色名称！', trigger: 'blur'
        }],
        identify: [{
          required: true, message: '请输入角色标识！', trigger: 'blur'
        }],
        description: [{
          required: true, message: '请输入角色描述！', trigger: 'blur'
        }]
      },
      showDialog: false,
      list: [],
      queryParmas: {
        menuId: null,
        role_name: '',
        page: 1,
        limit: 10
      },
      total: 0
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改角色' : '添加角色'
    }
  },
  created() {
    this.initData()
  },
  // mounted() {
  //   console.log(this.$refs.form)
  // },
  methods: {
    async submit() {
      const listId = await this.$refs.tree.getCheckedKeys()
      this.formData.authlist = listId
      this.$refs.form.validate(async isOK => {
        if (!isOK) return
        await this.formData.id ? this.doEdit() : this.doAdd()
        this.showDialog = false
      })
    },
    async addRole() {
      this.showDialog = true
      this.dataList = await getMenu()
      this.queryParmas.menuId = this.dataList[0].id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParmas.menuId)
      })
    },
    async editRole(id) {
      this.showDialog = true
      this.dataList = await getMenu(this.authlist)
      this.$refs.tree.defaultChecked = []
      const res = await getRoleDetail(id)
      console.log(res)
      this.formData = res
      // this.$nextTick(() => {
      function tranTreeToFlatData(treeData) {
        const flatData = []
        const traverse = (node, parentId) => {
          const { children, ...rest } = node // Destructuring the node object to get children and other properties
          flatData.push({ ...rest, parent_id: parentId })
          if (children) {
            children.forEach(child => traverse(child, node.id))
          }
        }
        treeData.forEach(node => traverse(node, null))
        return flatData
      }
      this.defaultChecked = tranTreeToFlatData(res.authlist).map(item => item.id)
      // this.$refs.tree.setCheckedNodes(this.defaultChecked)
      // })
      // this.formData = await getRoleDetail(id)
      // this.initData()
    },

    async doAdd() {
      await addRoleList(this.formData)
      this.$message.success('添加成功')
      this.showDialog = false
      this.queryParmas.page = 1
      this.initData()
    },
    async doEdit() {
      await updateRole(this.formData)
      this.$message.success('修改成功')
      this.showDialog = false
      this.queryParmas.page = 1
      this.initData()
    },
    // async editRow(rowId) {
    //   const res = await getRoleDetail(rowId)
    //   this.$refs.form.formData = res
    //   this.$refs.form.defaultChecked = transListToTreeData(res.authlist, 0)
    // },
    deleteRole(id) {
      this.$confirm('确定删除吗,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        if (this.list.length === 1 && this.queryParams.page > 1) {
          this.queryParams.page--
        }
        this.initData()
      }).catch(() => {
        return false
      })
    },
    btnSeacher() {
      this.queryParmas.page = 1
      this.initData()
    },
    cancelForm() {
      this.showDialog = false
    },
    btnReset() {
      this.queryParmas = {
        role_name: '',
        page: 1,
        limit: 10
      }
      this.initData()
    },
    resetForm() {
      this.formData = {
        role_name: '',
        identify: '',
        description: '',
        authlist: []
      }
      this.defaultChecked = []
      this.$refs.form.clearValidate()
    },
    async initData() {
      const res = await getRoleList(this.queryParmas)
      this.list = res.list
      this.total = res.total
    },
    async nodeClick(data) {
      this.queryParams.menuId = data.id
      this.initData()
    },
    handleCurrentChange(val) {
      this.queryParmas.page = val
      this.initData()
    },
    handleSizeChange(val) {
      this.queryParmas.limit = val
      this.queryParmas.page = 1
      this.initData()
    }
  }
}
</script>

<style lang="scss" scoped>
  .page-box {
    padding: 20px;
    .search-box,.tabbar-box {
      padding-top: 10px;
      margin-bottom: 20px;
      height: 50px;
    }
  }

</style>
